package cat.joronya.supermanager.service.substrImpl;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.auth.AuthenticationException;

import android.util.Log;

import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.ClosedChangesException;
import cat.joronya.supermanager.service.ClosedWebException;
import cat.joronya.supermanager.service.LoginParser;

public class LoginParserImpl implements LoginParser
{
	// login error STRING
	private static final String LOGIN_ERROR_STRING = "<img src='gif/registrar.gif' />";
	// supermanager tancat msg: "El juego estará cerrado durante unos minutos" STRING
	private static final String LOGIN_SM_TANCAT_STRING = "El juego estará cerrado durante unos minutos";
	// supermanaget tancat sense carcassa "<b>SUPERMANAGER CERRADO TEMPORALMENTE</b>" STRING
	private static final String LOGIN_SM_NC_TANCAT_STRING = "SUPERMANAGER CERRADO TEMPORALMENTE";
	// jornada STRING
	private static final String LOGIN_JORNADA_STRING = "<td class=\"blanca15\" background=\"gif/jornada.gif\" width=\"336\" height=\"25\"><img src=\"gif/pixel.gif\" width=\"10\" height=\"1\" border=\"0\">Jornada ";
	private static final String LOGIN_JORNADA_STOP_STRING = "<";
	// home info STRING
	private static final String LOGIN_INFO_STRING = "<td class=\"blanco\" width=\"336\">";
	private static final String LOGIN_INFO_STOP_STRING = "<!--";
	// next jornada STRING
	private static final String LOGIN_NEXT_JORNADA_STRING = "<span style=\"color:#FF6300;padding-left:10px;\">";
	private static final String LOGIN_NEXT_JORNADA_STOP_STRING = "ª";
	// duetime STRING
	private static final String LOGIN_DUETIME_STRING = "<span style=\"color:#68B8F5;padding-left:10px;\">";
	private static final String LOGIN_DUETIME_STOP_STRING = "<";
	// canvis tancats STRING
	private static final String LOGIN_CANVIS_TANCATS_STRING = "Cambios cerrados";

	// data parsed
	public String jornada = null;
	public String nextJornada = null;
	public Timestamp duetime = null;
	public String homeInfo = null;
	public int status = -1;
	
	public long parse(String html) 
	{
		long start = System.nanoTime();
		
		// login error?
		if( html.indexOf(LOGIN_ERROR_STRING) != -1 )
		{
			//throw new AuthenticationException();
			status = Supermanager.AUTH_ERROR_STATUS;
			return System.nanoTime()-start;
		}

		// mirem si supermanager tancat temporalment
		if( html.indexOf(LOGIN_SM_TANCAT_STRING) != -1 )
		{
			//throw new ClosedWebException();
			status = Supermanager.CLOSED_STATUS;
			return System.nanoTime()-start;
		}
		
		// mirem si supermanager tancat temporalment sense carcassa
		// mirem si estan els canvis tancats init page
		if( html.indexOf(LOGIN_SM_NC_TANCAT_STRING) != -1 )
		{
			//throw new ClosedWebException();
			status = Supermanager.CLOSED_STATUS;
			return System.nanoTime()-start;
		}
		
		// cerquem la jornada
		int jornadaStart = html.indexOf(LOGIN_JORNADA_STRING);
		int jornadaStop = html.indexOf(LOGIN_JORNADA_STOP_STRING, jornadaStart+LOGIN_JORNADA_STRING.length());
		if( jornadaStart == -1 || jornadaStop == -1 )
		{
			//throw new Exception();
			status = Supermanager.OTHER_ERROR_STATUS;
			return System.nanoTime()-start;
		}
		
		try
		{
			jornada = html.substring(jornadaStart+LOGIN_JORNADA_STRING.length(), jornadaStop);
		}catch(ArrayIndexOutOfBoundsException aioob)
		{
			//throw new Exception();
			status = Supermanager.OTHER_ERROR_STATUS;
			return System.nanoTime()-start;
		}

		// home info
		int homeInfoStart = html.indexOf(LOGIN_INFO_STRING,jornadaStop);
		int homeInfoStop = html.indexOf(LOGIN_INFO_STOP_STRING, homeInfoStart+LOGIN_INFO_STRING.length());
		homeInfo = html.substring(homeInfoStart+LOGIN_INFO_STRING.length(), homeInfoStop);

		int nextJornadaStart, nextJornadaStop, duetimeStart, duetimeStop=0;
		try
		{
			// next jornada
			nextJornadaStart = html.indexOf(LOGIN_NEXT_JORNADA_STRING, homeInfoStop);
			nextJornadaStop = html.indexOf(LOGIN_NEXT_JORNADA_STOP_STRING, nextJornadaStart+LOGIN_NEXT_JORNADA_STRING.length());
			nextJornada = html.substring(nextJornadaStart+LOGIN_NEXT_JORNADA_STRING.length(), nextJornadaStop);

			// duetime
			duetimeStart = html.indexOf(LOGIN_DUETIME_STRING, nextJornadaStop);
			duetimeStop = html.indexOf(LOGIN_DUETIME_STOP_STRING, duetimeStart+LOGIN_DUETIME_STRING.length());
			String duetimeString = html.substring(duetimeStart+LOGIN_DUETIME_STRING.length(), duetimeStop);

			Pattern p = Pattern.compile("([^\\s]*)\\s([^/]*)/([^,]*),\\s([^:]*):([^\\s]*)\\sh");
			Matcher m = p.matcher(duetimeString);
			if( m.find() ) 
			{	try
			{
				Calendar cToday = new GregorianCalendar();
				cToday.setTime(new Date());
				int year = cToday.get(Calendar.YEAR);
				// ??? els mesos conten començant per 0
				int month = Integer.parseInt(m.group(3))-1;
				// si el mes es menor q el de la data, next day es de l'any q ve
				Log.d(TAG, "LoginSync today month: "+cToday.get(Calendar.MONTH)+", date month: "+month);
				if( month < cToday.get(Calendar.MONTH) )
					year ++;
				int day = Integer.parseInt(m.group(2));
				int hour = Integer.parseInt(m.group(4));
				int minute = Integer.parseInt(m.group(5));
				Calendar calendar = new GregorianCalendar(year,month,day,hour,minute);
				duetime = new Timestamp(calendar.getTimeInMillis());
				Log.d(TAG,"loginSync duetime->year:"+year+", month: "+month+", day: "+day+
						", hour: "+hour+", minute: "+minute+
						"\nduetime: "+duetime+", getTime(): "+duetime.getTime()+
						"\ncalendar.getTimeInMillis(): "+calendar.getTimeInMillis());
			}
			catch(Exception e){}
			}
		}
		catch(Exception e){}

		// mirem si estan els canvis tancats
		if( html.indexOf(LOGIN_CANVIS_TANCATS_STRING,duetimeStop) != -1 )
		{
			//throw new ClosedChangesException();
			status = Supermanager.OPEN_NO_CHANGES_STATUS;
			return System.nanoTime()-start;
		}
		
		if( duetime == null)
		{
			//throw new ClosedChangesException();
			status = Supermanager.OPEN_NO_CHANGES_STATUS;
			return System.nanoTime()-start;
		}
		
		// si ens hem connectat marquem que estem online
		status = Supermanager.OPEN_STATUS;
		return System.nanoTime()-start;
    }
	
	public String getJornada() {
		return jornada;
	}

	public String getNextJornada() {
		return nextJornada;
	}

	public Timestamp getDuetime() {
		return duetime;
	}

	public String getHomeInfo() {
		return homeInfo;
	}

	public int getStatus() {
		return status;
	}

}
